/*
 * Copyright (C) 2014 Hortator
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package emergence.net.chat;

import emergence.net.chat.Chat.ChatMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import util.Logger;

/**
 * A client for connecting to a chat server.
 *
 * @author Nathan Templon
 */
public class ChatClient extends Thread {

    private static final Logger logger = Logger.getDefaultLogger(); // the logger to record what is going on

    private final Socket socket; // The socket for communications with the server
    private final PrintWriter out;
    private final BufferedReader in;
    
    private boolean running;

    private final List<ChatMessage> messages;
    private int lastIndexRetrieved = -1;

    /**
     * The standard constructor.
     *
     * @param host the IP address of the server as a String
     * @param port the port to connect to the server on
     *
     * @throws IOException throws an IOException if any of the connections to
     *                     the server fail
     */
    public ChatClient(String host, int port) throws IOException {
        this.messages = new ArrayList<>();
        this.socket = new Socket(host, port);
        this.out = new PrintWriter(socket.getOutputStream(), true);
        this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    
    @Override
    public void run() {
        running = true;
        
        try {
            socket.setSoTimeout(100);
        }
        catch (SocketException ex) {
            logger.log(ex);
        }
        
        while(running) {
            try {
                String line = in.readLine();
                messages.add(new ChatMessage(line));
            }
            catch (SocketTimeoutException ex) {
                
            }
            catch (IOException ex) {
                logger.log(ex);
            }
        }
    }

    /**
     * Sends the provided ChatMessage to the server.
     *
     * @param message the message to be sent to the server
     */
    public void sendMessage(ChatMessage message) {
        out.println(message.transmitString());
    }

    /**
     * Accesses any new messages that have been received from the chat server.
     *
     * @return Returns a list of new ChatMessages since the last time that
     *         newMessages() was called. Returns null if there are no new messages.
     */
    public synchronized List<ChatMessage> newMessages() {
        
        if (lastIndexRetrieved == -1 && messages.size() > 0) {
            lastIndexRetrieved = messages.size() - 1;
            return messages;
        }
        
        else if (lastIndexRetrieved < messages.size() - 1) {
            List<ChatMessage> newMessages = new ArrayList<>();
            for (int i = lastIndexRetrieved + 1; i < messages.size(); i++) {
                newMessages.add(messages.get(i));
            }
            lastIndexRetrieved = messages.size() - 1;
            return newMessages;
        }

        // If there are no new messages, return null
        return null;
    }

    /**
     * Closes this ChatClient
     */
    public synchronized void close() {
        try {
            running = false;
            in.close();
            out.close();
            socket.close();
        }
        catch (IOException ex) {
            logger.log(ex);
        }
    }
}
